//
//  Ball.m
//  billiards
//
//  Created by Matsumae Kentaro on 12/03/20.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Ball.h"
#import "SinglePlayer.h"
#import <math.h>

int _currentBallTag;


@implementation Ball

@synthesize isInHall,moveUser;
@synthesize heart = _heart;
@synthesize damage = _damage;

-(id)initWithWorld:(b2World*)world at:(CGPoint)pos touchable:(BOOL)touchable color:(ccColor3B)color type:(int) type {
    if ((self = [super init])) {
        [self createBallInWorld:world at:pos color:color type:type];
        canTouch = YES;
        world_ = world;
        _heart = arc4random() % 3 + 2;
        _damage = arc4random() % 4 + 1;
        [self scheduleUpdate];
    }
    return self;
}

+(id)ballWithWorld:(b2World*)world at:(CGPoint)pos touchable:(BOOL)touchable type:(int) type {
    return [[[self alloc] initWithWorld:world at:pos touchable:touchable color:ccWHITE type:type] autorelease];
}

+(id)ballWithWorld:(b2World*)world at:(CGPoint)pos color:(ccColor3B)color type:(int) type{
    return [[[self alloc] initWithWorld:world at:pos touchable:NO color:color type:type] autorelease];
}

-(void)delloc {
    NSLog(@"dealoc ball");
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super dealloc];
}

-(BOOL) checkCanTouchOnScreen{
    for(b2Body *b = world_->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            if((b->IsAwake()))
            {
                return NO;
            }
        }        
    }
    return YES;
}

+(CGFloat)ballWidth {
    CCSprite* tmpSprite = [CCSprite spriteWithFile:@"blue_ball.png"];
    return tmpSprite.contentSize.width;
}

-(void)resetColor {
    sprite.color = originalColor;
}

-(void)createBallInWorld:(b2World*)world at:(CGPoint)pos color:(ccColor3B)color type:(int) type {
    
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position = [Helper toMeters:pos];
    bodyDef.bullet = YES;
    
    bodyDef.angularDamping = 1.8f;
    bodyDef.linearDamping = 1.8f;
    
    ballRadius = [Ball ballWidth] * 0.5f;
    float radiusInMeters = (ballRadius / PTM_RATIO) ;
    
    b2CircleShape shape;
    shape.m_radius = radiusInMeters;
    
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &shape;
    fixtureDef.density = 0.5f;
    fixtureDef.friction = 1.0f;
    fixtureDef.restitution = 1.0;
    
    NSString *fileName = @"blue_ball.png";
    if (type==2) {
        fileName = @"red_ball.png";
    }
    
    [super createBodyInWorld:world bodyDef:&bodyDef fixtureDef:&fixtureDef spriteFileName:fileName];
    
    sprite.position = pos;
    sprite.color = color;
    
    originalColor = color;

    moveToFinger = NO;
}

-(void) applyForceTowardsFinger {
    for(b2Body *b = world_->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            CCSprite *ballData = (CCSprite *)b->GetUserData();
            if (ballData.tag==self.tag) {
                b2Vec2 bodyPos = b->GetWorldCenter();
                b2Vec2 fingerPos = [Helper toMeters:fingerLocation];
                
                b2Vec2 bodyToFinger = fingerPos - bodyPos;
                
                b2Vec2 force = 5.0 * bodyToFinger;
                
                b->SetLinearVelocity(force);
                b->SetAngularVelocity(0.0f);
                break;
            }
        }        
    }
}

-(void) removeTouchDelete{
    [self stopAllActions];
    for(b2Body *b = world_->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            b->SetLinearVelocity(b2Vec2(0.0f, 0.0f));
            b->SetAngularVelocity(0.0f);
        }        
    }
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
}

-(BOOL)isInHall:(CGPoint)pos {
    if (pos.x<=0 || pos.x>=1024) {
        return YES;
    }
    if (pos.y<=0 || pos.y>=768) {
        return YES;
    }
    return NO;
}


-(void) update:(ccTime)delta {
    CGPoint pos = sprite.position;
    if ([self isInHall:pos]) {
        isInHall = true;
    }
}

-(BOOL) isTouchForMe:(CGPoint)location {
    return abs(sprite.position.x - location.x) < ballRadius*2 && abs(sprite.position.y - location.y) < ballRadius*2;
}

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    if (![self checkCanTouchOnScreen]) {
        return NO;
    }
    
    CGPoint location = [Helper locationFromTouch:touch];
    moveToFinger = YES;
    fingerLocation = location;
    
    body->SetLinearVelocity(b2Vec2(0.0f, 0.0f));
    body->SetAngularVelocity(0.0f);
    
    if (self.tag<=7) {
        ballTracer = [BallTracer newTracerWithTouchLocation:fingerLocation ballLocation:self.sprite.position type:1];
        [self addChild:ballTracer];
        
        CCSprite *arrow = [CCSprite spriteWithFile:@"arrow_hollow_down.png"];
        arrow.position = ccp(self.sprite.position.x,self.sprite.position.y);
        arrow.textureRect = CGRectMake(0, 0, 300, 300);
        arrow.tag = 999;
        arrow.scaleY = 0.1;
        arrow.anchorPoint = ccp(0.5,0.5);
        [self.parent addChild:arrow];
    }
    else {
        ballTracer = [BallTracer newTracerWithTouchLocation:fingerLocation ballLocation:self.sprite.position type:2];
        [self addChild:ballTracer];
    }
    _currentBallTag = [self tag];
    NSLog(@"current ball tag: %d", _currentBallTag);
    return YES;
}

-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    if (moveToFinger) {
        CGPoint fingerLocation2 = [Helper locationFromTouch:touch];
        
        CCSprite *arrow = (CCSprite *)[self.parent getChildByTag:999];
        //arrow.position = ccp(arrow.position.x,arrow.position.y+(fingerLocation.y-fingerLocation2.y)/2);
        NSLog(@"finger:%f",(fingerLocation.y-fingerLocation2.y));
        float scale = arrow.scaleY + (fingerLocation.y-fingerLocation2.y)/10;
        if (scale>=1) {
            scale = 1;
        }
        else if (scale<=0.1) {
            arrow.rotation = 180;
            scale = 0.1;
        }
        arrow.scaleY = scale;
        arrow.rotation = arrow.rotation - (fingerLocation2.x - fingerLocation.x)/2;
        //arrow.textureRect = CGRectMake(0, 0, 300, arrow.textureRect.size.height + (fingerLocation.y - fingerLocation2.y));
        
        fingerLocation = [Helper locationFromTouch:touch];
        //NSLog(@"fingerLocation:%f",fingerLocation.y);
        ballTracer.touchLocation = fingerLocation;
        
        /*
        if (self.tag<=7) {
            ballTracer.touchLocation = CGPointMake(fingerLocation.x, 768-fingerLocation.y);
        }
        else {
            ballTracer.touchLocation = CGPointMake(fingerLocation.x, self.sprite.position.y-fingerLocation.y);
        }*/
        
    }
}

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    if (moveToFinger) {
        [self applyForceTowardsFinger];
        moveToFinger = NO;
              
        [self removeChild:ballTracer cleanup:YES];
        [self schedule:@selector(checkToUpdateLabel) interval:0.01];
        
        [self.parent removeChildByTag:999 cleanup:YES];
    }
}

-(void) checkToUpdateLabel{
    if ([self checkCanTouchOnScreen]) {
        [self unschedule:@selector(checkToUpdateLabel)];
        [(SinglePlayer *)self.parent endMovingWithTag:self.tag];
    }
}

@end
